# -*- coding: utf-8 -*-
"""info提供app，日志，db"""
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask import g
from flask import render_template
from flask.ext.session import Session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf import CSRFProtect
from redis import StrictRedis
from config import configDict

db = SQLAlchemy()
redis_store = None  # type:StrictRedis


def setup_log(env):
    """配置日志，参数为启动文件传入的环境"""
    # 设置日志的记录等级
    logging.basicConfig(level=configDict[env].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(env):
    """通过传入不同的环境，初始化其对应配置的应用实例"""
    setup_log(env)
    app = Flask(__name__)
    # 加载配置
    app.config.from_object(configDict[env])
    # 初始化db
    db.init_app(app)
    """开启项目CSRF保护"""
    CSRFProtect(app)
    # 初始化Session
    Session(app)
    # 初始化redis
    global redis_store
    redis_store = StrictRedis(host=configDict[env].REDIS_HOST, port=configDict[env].REDIS_PORT, decode_responses=True)
    # 给app添加index_class过滤器
    from info.utills.common import index_class
    app.add_template_filter(index_class, 'index_class')
    # 注册蓝图到app
    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    from info.modules.news import detail_blue
    app.register_blueprint(detail_blue)

    from info.modules.profile import user_blue
    app.register_blueprint(user_blue)

    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    from info.utills.common import after_request
    after_request(app)

    # 添加404异常捕获
    from info.utills.common import check_user_login
    @app.errorhandler(404)
    @check_user_login
    def page_not_found(e):
        from flask import current_app
        current_app.logger.error(e)
        user = g.user
        data = {"user": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

    return app
